#include <string>
#include <vector>

using namespace std;


/**
 * @brief 71. 简化路径
 * https://leetcode.cn/problems/simplify-path/
 */
class Solution {
public:
    string simplifyPath(string path) {
        auto split = [](const string& s, char delim) -> vector<string> {
            vector<string> res;
            string curr;
            for (const char& c : s) {
                if (c == delim) {
                    res.emplace_back(curr);
                    curr.clear();
                } else {
                    curr += c;
                }
            }
            res.emplace_back(curr);
            return res;
        };

        vector<string> names = split(path, '/');
        vector<string> stk;
        for (string& name : names) {
            if (name == "..") {
                if (!stk.empty()) stk.pop_back();
            } else if (!name.empty() && name != ".") {
                stk.emplace_back(name);
            }
        }

        string res;
        if (stk.empty()) res = "/";
        else {
            for (string& name : stk) {
                res += "/" + name;
            }
        }

        return res;
    }
};
